<template>
    <div style="height: 100%; overflow-y: auto">
        <Header style="background: #fff; box-shadow: 0 1px 1px rgba(0,0,0,.1); height: 40px; line-height: 40px; padding: 0; margin-bottom: 20px">
            <h3 style="float: left; font-size:16px">隐患基本信息</h3>
            <ButtonGroup style="float: right">
                <Button @click="saveInfo" type="warning" style="background: #EF5350;" :loading="buttonLoading">
                    <Icon type="ios-bookmark" />
                    保存
                </Button>
                <Button @click="$router.go(-1)">
                    返回
                    <Icon type="ios-arrow-forward" />
                </Button>
            </ButtonGroup>
        </Header>
        <div :style="{overflowY: 'auto', overflowX: 'hidden', height:  divHeight+'px'}">
            <Divider orientation="left" style="margin-top: 5px" >请选择条目进行排查</Divider>
            <Row>
                <i-col>
                    <Form :label-width="100" ref="formInline" :model="formInline">
                        <Row :gutter="16" class="query-form">
                            <i-col span="8">
                                <FormItem label="隐患编号：" prop="name">
                                    <Input v-model="formInline.name"  placeholder="请填写隐患编号"/>
                                </FormItem>
                            </i-col>
                            <i-col span="8">
                                <FormItem label="排查内容：" prop="remark">
                                    <Input v-model="formInline.content" placeholder="请填写排查内容"/>
                                </FormItem>
                            </i-col>
                            <i-col span="8">
                                <div style="float: right">
                                    <Button class="ivu-btn-reset" style="margin-left: 10px" @click="cancel">重置</Button>
                                    <Button class="ivu-btn-query" icon="md-search"  @click="query">查询</Button>
                                </div>
                            </i-col>
                        </Row>
                    </Form>
                    <Table ref='table' :loading="loading" border :columns="columns" no-data-text="请选择隐患条目分类"
                           :data="infos" width="100%" :height="tableHeight"  highlight-row stripe size="small"></Table>
<!--                    <Row type="flex" justify="end" >-->
<!--                        <i-col>-->
<!--                            <Page :total="pagedata.total" :current="pagedata.currentPage" :page-size="pagedata.pageSize"-->
<!--                                  @on-page-size-change="pageSizeChange" @on-change="pageChange" :page-size-opts="pageSizeArray" show-total show-sizer show-elevator />-->
<!--                        </i-col>-->
<!--                    </Row>-->
                </i-col>
            </Row>

<!--            <Split v-model="split1"  :style="{height:SplitHeight+'px'}"  class="demo-split">-->
<!--                <div slot="left" style="height: 90%; overflow-y: auto; overflow-x: hidden; padding: 5px">-->
<!--                    <Tree ref="tree" :data="treeData" :load-data="loadApsgItemType" :render="renderContent" style="width: 100%"></Tree>-->
<!--                </div>-->
<!--                <div slot="right" class="demo-split-pane">-->
<!--                    -->
<!--                </div>-->
<!--            </Split>-->
        </div>
    </div>
</template>

<script>

    import {Api} from '../../../api'
    var cascaderDom = () => import('@/components/cascader-dom.vue');
    import {sessionStorage} from '@/common/cacheUtils.js';

    export default {
        name: "hidHazardDetail",
        components:{
            cascaderDom
        },
        data(){
            return {
                SplitHeight: 0,
                tableHeight: 0,
                buttonLoading: false,
                isCustom: false,
                showItem: false,
                loading: false,
                formInline: {},
                showHidList: false,
                split1: 0.3,
                formData: {},
                ruleCustom: {
                    proId: [
                        {
                            required: true,
                            message: '  ',
                            trigger: 'blur,change'
                        }
                    ],
                    remark: [
                        {
                            required: true,
                            message: '  ',
                            trigger: 'blur,change'
                        }
                    ],
                    content: [
                        {
                            required: true,
                            message: '  ',
                            trigger: 'blur,change'
                        }
                    ],
                    level: [
                        {
                            required: true,
                            message: '  ',
                            trigger: 'blur,change'
                        }
                    ],
                    recPeriod: [
                        {
                            type: 'integer',
                            required: true,
                            message: '  ',
                            trigger: 'blur,change'
                        }
                    ]
                },
                fileUrl: '',
                hazardId: '',
                existOrgId: '',
                columns: [
                    {
                        type: 'index',
                        title: '序号',
                        width: 80,
                        align: 'center',
                    },
                    {
                        title: '专业',
                        align: 'center',
                        key: 'idApitemtype',
                        width: 100,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.idApitemtype || '--')
                            ]);
                        }
                    },
                    {
                        title: '类型',
                        align: 'center',
                        key: 'aptypeclass',
                        width: 120,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.aptypeclass || '--')
                            ]);
                        }
                    },
                    {
                        title: '项目',
                        align: 'center',
                        key: 'aptype',
                        width: 200,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.aptype || '--')
                            ]);
                        }
                    },
                    {
                        title: '隐患编号',
                        align: 'center',
                        key: 'name',
                        width: 150,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.name || '--')
                            ]);
                        }
                    },
                    {
                        title: '隐患等级',
                        align: 'center',
                        key: 'level',
                        width: 100,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.level || '--')
                            ]);
                        }
                    },
                    {
                        title: '排查内容',
                        align: 'center',
                        key: 'content',
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.content || '--')
                            ]);
                        }
                    },
                    {
                        title: '操作',
                        align: 'center',
                        fixed: 'right',
                        width: 180,
                        render: (h, params) => {
                            let mValue= 0;
                            this.apsgItemList.map((i)=>{
                                if(i.id == params.row.id&&i.status!= undefined){
                                    mValue = i.status;
                                }
                            })
                            return h('RadioGroup', {
                                props: {
                                    value: mValue
                                },
                                on:{
                                    'on-change':(status)=>{
                                        let data = params.row;

                                        // console.log(this.apsgItemList.indexOf(params.row));
                                        this.infos.map((i)=>{
                                            if(i.id == params.row.id) i.status = status;
                                        })

                                        // // this.apsgItemList.splice(this.apsgItemList.indexOf(data), 1);
                                        params.row.status = status;
                                        // this.apsgItemList.push(data);
                                    }
                                }
                            },[
                                h('Radio', {
                                    props: {
                                        "label": 0,
                                    },
                                }, '安全'),
                                h('Radio', {
                                    props: {
                                        "label": 1
                                    }
                                }, '有隐患'),
                            ]);
                        }
                    }
                ],
                infos: [],
                treeData: [
                    {
                        title: '隐患条目分类',
                        id: 1,
                        expand: true,
                        type: 1,
                        children: [],
                    }
                ],
                selectData: {},
                pagedata: {
                    total: 0,
                    pageSize: 10,
                    currentPage: 1,
                    total2: 0,
                    pageSize2: 10,
                    currentPage2: 1
                },
                pageSizeArray: [10, 20, 50],
                apsgItemList: [],
                rootOrgId: '',
                divHeight: 0,
                ifList: [
                    {
                        id: 0,
                        label: '是'
                    },
                    {
                        id: 1,
                        label: '否'
                    }
                ],
                proId: '',
                levelList: [
                    {
                        id: 'Ⅰ',
                        label: 'Ⅰ'
                    },
                    {
                        id: 'Ⅱ',
                        label: 'Ⅱ'
                    },
                    {
                        id: 'Ⅲ',
                        label: 'Ⅲ'
                    },
                    {
                        id: 'Ⅳ',
                        label: 'Ⅳ'
                    }
                ],
                fileList: [],
                roleUserList: [],
                manageRoute: false
            }
        },
        mounted() {
            this.loadData();
            let user = sessionStorage('userId').getObject('userId');
            this.rootOrgId =  user.orgInfo.parentId;
            this.formData.proId = user.orgInfo.orgId;
            this.proId = user.orgInfo.orgId;
            this.divHeight = window.innerHeight - 180;
            this.SplitHeight = window.innerHeight - 260;
            this.tableHeight = window.innerHeight - 280;
            // this.qeuryApsgItemType();
            this.query();
        },
        watch:{
            "existOrgId": function (qw, er) {
                if(qw){
                    this.showHidList = true;
                }
            },
            "proId": function (qw, er){
                let user = sessionStorage('userId').getObject('userId');
                if(qw == user.orgInfo.orgId){
                    this.manageRoute == true;
                }else{
                    this.manageRoute == false;
                }
            }
        },
        methods:{
            loadData(){
                let user = sessionStorage('userId').getObject('userId');
                this.formData = {
                    userName: user.userName,
                    operatorId: user.userId,
                    operatorOrgId: user.orgInfo.orgId,
                    reportDateStr: this.formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss'),
                    orgName: user.orgInfo.orgName,
                    orgid: user.orgInfo.orgId,
                    id: this.uuid()
                };
                this.fileUrl = Api.uploadPTWFiles  + '/' + this.formData.id + '/files/picture/report'
            },
            setOrgName(data){
                this.formData.proId = data[data.length - 1];
                this.proId = data[data.length - 1];
            },
            saveInfo(){
                this.buttonLoading = true;
                let user = sessionStorage('userId').getObject('userId');
                if(user.orgInfo.orgId == this.proId)
                this.formData.revisemaindept = this.proId;
                this.formData.apsgItem = this.infos;
                if(this.$route.query.generateType == "2"){
                    this.formData.taskId = this.$route.query.taskId;
                }
                this.formData.generateType = this.$route.query.generateType;
                this.formData.type = 1;
                this.$http.post(Api.apsgInverstigation,this.formData).then(function(response){
                    this.buttonLoading = false;
                    if(response.data.status == 200) {
                        this.$router.go(-1);
                        this.$Message.success({content: '保存成功', duration: 4 });
                    }else{
                        this.$Message.error({content: '保存失败', duration: 4 });
                    }
                });
            },
            loadApsgItemType(item, callback){
                let user = sessionStorage('userId').getObject('userId');
                this.$http.get(Api.getApsgItemTypesByItemPlanId+"/"+this.$route.query.itemPlanId+"/"+item.id).then(res => {
                    callback(res.data);
                }).catch(e => {
                    this.$Message.error('请求失败');
                })
            },
            cancel(){
                this.formInline = {};
                this.query();
            },
            query(){
                this.loading = true;
                let data = {
                    startPage: this.pagedata.currentPage,
                    pageSize: this.pagedata.pageSize,
                };
                data = Object.assign(data,JSON.parse(JSON.stringify(this.formInline)));
                this.$http.get(Api.getApsgItemsByItemPlanId + "/" + this.$route.query.itemPlanId, {params: data}).then(res => {
                    this.infos = res.data;
                    this.apsgItemList = [];
                    this.infos.map((i)=>{ i.status = 0; });
                    this.loading = false;
                }).catch(e => {
                    this.$Message.error('请求失败');
                })
            },
            qeuryApsgItemType(){
                this.$http.get(Api.getApsgItemTypesByPositionId + '/' + this.$route.query.itemPlanId +"/1").then(res => {
                    this.treeData[0].children = res.data;
                }).catch(e => {
                    this.$Message.error('请求失败');
                })
            },
            renderContent (h, { root, node, data }) {
                let icon = "ios-folder";
                return h('span', {
                    style: {
                        display: 'inline-block',
                        cursor: "pointer",
                        color: node.node.selected ? "#2d8cf0" : "black" //根据选中状态设置样式
                    },
                    on:{
                        click: () => {
                            this.selectData = data;
                            this.query();
                            if (!node.node.selected)  this.$refs.tree.handleSelect(node.nodeKey);
                        },
                    }
                },
                 [
                    h('span', [
                        h('Icon', {
                            props: {
                                type: icon,
                            },
                            style: {
                                marginRight: '5px',
                                color: '#FF7F00'
                            }
                        }),
                        h('span', data.title)
                    ])
                ]
                );
            },
            pageSizeChange(pageSize){
                this.pagedata.pageSize = pageSize;
                this.query();
            },
            pageChange(pageNum){
                this.pagedata.currentPage = pageNum;
                this.query();
            },
            beforeUpload (file) {
                let keyID = Math.random().toString().substr(2);
                file['keyID'] = keyID;
                this.fileList.push(file);
                return false;
            },
            removeFile(keyID){
                this.fileList = this.fileList.filter(item => {
                    return item.keyID != keyID
                })
            },
            uuid() {
                let s = [];
                let hexDigits = "0123456789abcdef";
                for(let i = 0; i < 32; i++) {
                    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
                }
                s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
                s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
                let uuid = s.join("");
                return uuid
            },
            formatDate(date, fmt) {
                if (typeof date == 'string') {
                    return date;
                }
                if (!fmt) fmt = "yyyy-MM-dd hh:mm:ss";
                if (!date || date == null) return null;
                let o = {
                    'M+': date.getMonth() + 1, // 月份
                    'd+': date.getDate(), // 日
                    'h+': date.getHours(), // 小时
                    'm+': date.getMinutes(), // 分
                    's+': date.getSeconds(), // 秒
                    'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
                    'S': date.getMilliseconds() // 毫秒
                }
                if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
                for (let k in o) {
                    if (new RegExp('(' + k + ')').test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
                }
                return fmt
            },
        }
    }
</script>

<style scoped>
    @import '../../../index.css';
    .demo-split{
        height: 200px;
        border: 1px solid #dcdee2;
    }
    .demo-split-pane{
        padding: 10px;
    }
    .demo-drawer-footer{
        position: fixed;
        right: 0;
        bottom: 0;
        z-index: 9;
        width: 100%;
        height: 56px;
        padding: 0 24px;
        line-height: 56px;
        background: #fff;
        border-top: 1px solid #e8eaec;
        -webkit-box-shadow: 0 -1px 2px rgba(0,0,0,.03);
        box-shadow: 0 -1px 2px rgba(0,0,0,.03);
    }
    .ivu-footer-toolbar-right {
        float: right;
    }
</style>
